"""
安全功能演示路由
展示API速率限制和输入验证的使用方法
"""

from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel, Field, EmailStr
from typing import Optional
from src.services import rate_limit, validate_input, InputValidator, get_current_active_user
from src.models.user import User

router = APIRouter(prefix="/security-demo", tags=["安全演示"])

class UserCreateRequest(BaseModel):
    """用户创建请求模型"""
    username: str = Field(..., min_length=3, max_length=50)
    email: EmailStr
    phone: Optional[str] = None
    description: Optional[str] = Field(None, max_length=500)

class ContactRequest(BaseModel):
    """联系表单请求模型"""
    name: str = Field(..., min_length=1, max_length=100)
    email: EmailStr
    message: str = Field(..., min_length=2, max_length=1000)

@router.get("/rate-limited-endpoint")
@rate_limit(limit=5, window=60)  # 限制每分钟最多5次请求
async def rate_limited_endpoint(request: Request):
    """
    演示API速率限制功能的端点
    
    限制每个客户端每分钟最多访问5次
    """
    return {
        "message": "这是一个受速率限制保护的端点",
        "client_ip": request.client.host if request.client else "unknown"
    }

@router.post("/validate-user-input")
@validate_input(
    username=[InputValidator.validate_length, InputValidator.validate_alphanumeric],
    email=[InputValidator.validate_email],
    phone=[InputValidator.validate_phone]
)
async def validate_user_input(request: UserCreateRequest):
    """
    演示输入验证功能的端点
    
    验证用户名、邮箱和电话号码格式
    """
    return {
        "message": "输入验证通过",
        "data": request.dict()
    }

@router.post("/contact-form")
@rate_limit(limit=3, window=300)  # 限制每5分钟最多3次请求
async def contact_form(contact: ContactRequest):
    """
    演示联系表单处理的端点
    
    包含速率限制和输入验证
    """
    # 这里可以添加发送邮件等业务逻辑
    return {
        "message": "感谢您的留言，我们会尽快回复您",
        "received": contact.dict()
    }

@router.get("/protected-endpoint")
@rate_limit(limit=10, window=60)  # 限制每分钟最多10次请求
async def protected_endpoint(current_user: User = Depends(get_current_active_user)):
    """
    演示受保护端点的速率限制
    
    需要认证用户且有速率限制
    """
    return {
        "message": "这是一个需要认证且受速率限制保护的端点",
        "user": current_user.username
    }